package org.cagui.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;

import org.cagui.core.KeyStoreManager;
import org.cagui.listener.KeyStoreRadioButtonListener;

public class KeyStoreDetails extends JFrame implements ActionListener {

	KeyStoreManager keyStoreManager;
	KeyStoreRadioButtonListener keyStoreRadioButtonListener;

	JFrame frame;

	public KeyStoreDetails(KeyStoreManager keyStoreManager) {

		this.keyStoreManager = keyStoreManager;

		frame = this;

		setSize(520, 400);
		setTitle("KeyStoreDetails: " + keyStoreManager.getActPath());

		// Top button panel
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		buttonPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

		JButton importKey;
		JButton deleteKey;
		JButton openKey;

		// Adding buttons
		openKey = new JButton("Show selected key details");
		openKey.setActionCommand("openKey");
		openKey.addActionListener(this);

		importKey = new JButton("Import key");
		importKey.setActionCommand("importKey");
		importKey.addActionListener(this);

		deleteKey = new JButton("Delete key");
		deleteKey.setActionCommand("deleteKey");
		deleteKey.addActionListener(this);

		buttonPanel.add(openKey);
		buttonPanel.add(Box.createRigidArea(new Dimension(10, 10)));

		/*
		 * buttonPanel.add(importKey); buttonPanel.add(Box.createRigidArea(new
		 * Dimension(10, 10)));
		 */

		buttonPanel.add(deleteKey);

		keyStoreRadioButtonListener = new KeyStoreRadioButtonListener();

		// LISTNING KEYS
		ButtonGroup group = new ButtonGroup();
		JPanel radioButtonPanel = new JPanel();
		radioButtonPanel.setLayout(new BoxLayout(radioButtonPanel,
				BoxLayout.Y_AXIS));
		radioButtonPanel.setBorder(new EmptyBorder(20, 80, 20, 80));

		radioButtonPanel.add(new JLabel("Avaliable keys:"));

		List<String> children = new ArrayList<String>();
		try {

			children.addAll(keyStoreManager.getActualKeyStoreContent());

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (children == null) {
		} else {

			for (int i = 0; i < children.size(); i++) {

				String keyName = children.get(i);

				JRadioButton keyStoreButton;

				keyStoreButton = new JRadioButton(i + 1 + ". " + keyName);

				keyStoreButton.setMnemonic(KeyEvent.VK_B);
				keyStoreButton.setActionCommand(keyName);
				keyStoreButton.addActionListener(keyStoreRadioButtonListener);
				group.add(keyStoreButton);
				radioButtonPanel.add(keyStoreButton);

			}
			if (children.size() == 0)
				radioButtonPanel.add(new JLabel(" > No keys avaliable"));

		}

		JPanel framePanel = new JPanel();
		framePanel.setLayout(new BoxLayout(framePanel, BoxLayout.Y_AXIS));
		framePanel.add(buttonPanel);

		Box radioButtonBox = Box.createHorizontalBox();
		radioButtonBox.add(radioButtonPanel);
		radioButtonBox.add(Box.createHorizontalGlue());
		framePanel.add(radioButtonBox);
		this.setContentPane(framePanel);

		this.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		Object actionCommand = event.getActionCommand();
		String keyName = keyStoreRadioButtonListener.getSelected();

		if (actionCommand.equals("openKey")) {
			if (!keyName.equals("none")) {

				boolean flag = true;

				String s = (String) JOptionPane.showInputDialog(frame,
						"Password for chosen key, with name: \n" + keyName,
						"Enter Password", JOptionPane.PLAIN_MESSAGE, null,
						null, "");

				if ((s != null) && (s.length() > 0)) {
					if (keyStoreManager.isPasswordValidForKey(keyName, s)) {
						flag = false;
						String key = "";
						try {
							key = keyStoreManager.getKeyContent(keyName, s);
							new KeyData(key);
						} catch (Exception e) {
						}
					}
					if (flag) {
						JOptionPane.showMessageDialog(frame,
								"Password is incorrect!", "Wrong password",
								JOptionPane.ERROR_MESSAGE);
					}

				}

			}
		} else if (actionCommand.equals("importKey")) {

		} else if (actionCommand.equals("deleteKey")) {

			if (!keyName.equals("none")) {
				boolean flag = true;

				String s = (String) JOptionPane.showInputDialog(frame,
						"Password for chosen key, with name: \n" + keyName,
						"Enter Password", JOptionPane.PLAIN_MESSAGE, null,
						null, "");

				if ((s != null) && (s.length() > 0)) {
					if (keyStoreManager.isPasswordValidForKey(keyName, s)) {
						flag = false;
						int n = JOptionPane.showConfirmDialog(frame,
								"Are you sure?", "Delete key?",
								JOptionPane.YES_NO_OPTION);

						if (n == JOptionPane.YES_OPTION) {

							try {
								keyStoreManager.removeKeyFromKeyStore(keyName, keyStoreManager.getActKeyStore());
								keyStoreManager.getActKeyStore().store( new FileOutputStream(keyStoreManager.getActPath()), keyStoreManager.getActPass().toCharArray());
								frame.dispose();
								new KeyStores(keyStoreManager);
							} catch (KeyStoreException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							/*File file = new File(KeyStoreManager.path + keyName);

							file.delete();

							;*/ catch (NoSuchAlgorithmException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (CertificateException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					if (flag) {
						JOptionPane.showMessageDialog(frame,
								"Password is incorrect!", "Wrong password",
								JOptionPane.ERROR_MESSAGE);
					}
				} else {
					JOptionPane.showMessageDialog(frame,
							"You have to select key to delete!",
							"Empty selection", JOptionPane.WARNING_MESSAGE);
				}
			}

		}
	}
}
